<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { useGlobalStore } from '@/stores/global'
  import { topList, page as getBlogPage } from '@/api/blog'
  import { list as getTagList } from '@/api/tag'
  import { tree as getCategoryTree } from '@/api/category'

  import type { FeaturedPost, BlogPost, Tag, Comment } from '@/types/blog'
  import type { Blog, Tag as ApiTag, Category } from '@/types/api'
  import HeroSection from '@/components/home/HeroSection.vue'
  import FeaturedPosts from '@/components/home/FeaturedPosts.vue'
  import RecentPosts from '@/components/home/RecentPosts.vue'
  import SiteStats from '@/components/home/SiteStats.vue'
  import PopularTags from '@/components/home/PopularTags.vue'
  import PopularCategories from '@/components/home/PopularCategories.vue'
  import RecentComments from '@/components/home/RecentComments.vue'
  import { User } from '@/types/user'

  const router = useRouter()
  const globalStore = useGlobalStore()
  const user = ref<User | null>(null)

  // 页面数据
  const loading = ref(true)
  const featuredPosts = ref<FeaturedPost[]>([])
  const recentPosts = ref<BlogPost[]>([])
  const popularTags = ref<(Tag & { id: string })[]>([])
  const popularCategories = ref<Category[]>([])
  const recentComments = ref<Comment[]>([])

  // 数据转换函数
  const transformBlogToFeaturedPost = (blog: Blog, _index: number): FeaturedPost => {
    return {
      id: blog.id,
      title: blog.title,
      summary: blog.summary || '',
      coverImage: `/api/portal/file/${blog.backgroundImg}`,
      publishDate: blog.pushTime,
      category: blog.category?.name || '默认分类',
      tags: blog.tags?.map(tag => tag.name) || [],
      readTime: `${Math.ceil((blog.mkContent?.length || 0) / 500)}分钟`,
      views: blog.views || 0,
      likes: blog.likes || 0,
    }
  }

  const transformBlogToBlogPost = (blog: Blog): BlogPost => {
    const result = {
      id: blog.id,
      title: blog.title,
      summary: (blog.summary || '').replace(/\n/g, ' ').trim(), // 移除换行符
      publishDate: blog.pushTime,
      category: blog.category?.name || '默认分类',
      tags: blog.tags?.map(tag => tag.name) || [],
      readTime: `${Math.ceil((blog.mkContent?.length || 0) / 500)}分钟`,
      views: blog.views || 0,
      likes: blog.likes || 0,
    }
    return result
  }

  const transformApiTagToTag = (tag: ApiTag): Tag & { id: string } => {
    // 预定义的标签颜色（作为后备方案）
    const tagColors: { [key: string]: string } = {
      'Vue.js': '#4FC08D',
      Vue: '#4FC08D',
      JavaScript: '#F7DF1E',
      TypeScript: '#3178C6',
      React: '#61DAFB',
      CSS: '#1572B6',
      'Node.js': '#339933',
      Webpack: '#8DD6F9',
      前端工程化: '#FF6B6B',
      HTML: '#E34C26',
      Java: '#007396',
      Spring: '#6DB33F',
      Python: '#3776AB',
      Git: '#F05032',
      Docker: '#2496ED',
      MySQL: '#4479A1',
      Redis: '#DC382D',
      Linux: '#FCC624',
      Nginx: '#009639',
    }

    return {
      id: tag.id,
      name: tag.name,
      count: tag.count,
      // 优先使用后端返回的颜色，如果没有则使用预定义颜色，最后才使用随机颜色
      color:
        tag.color || tagColors[tag.name] || '#' + Math.floor(Math.random() * 16777215).toString(16),
    }
  }

  // 初始化数据
  const initData = async () => {
    try {
      loading.value = true

      // 记录开始时间用于性能统计
      const startTime = performance.now()

      // 并行获取所有数据（用户信息通过ensureUserInfo统一获取）
      const [userInfoResult, topPostsResult, recentBlogsResult, tagsResult, categoriesResult] =
        await Promise.allSettled([
          // 统一通过globalStore.ensureUserInfo获取用户信息
          globalStore.ensureUserInfo(), // 中文备注：统一用户信息获取方式，避免重复请求
          topList({}),
          getBlogPage({ pageSize: 6, pageNum: 1 }),
          getTagList(),
          getCategoryTree(),
        ])

      user.value = userInfoResult.status === 'fulfilled' ? userInfoResult.value : null
      // 处理精选文章
      if (topPostsResult.status === 'fulfilled') {
        const topPosts = topPostsResult.value
        if (topPosts && topPosts.length > 0) {
          featuredPosts.value = topPosts.map((blog, index) =>
            transformBlogToFeaturedPost(blog, index)
          )
        }
      } else {
        console.warn('获取精选文章失败:', topPostsResult.reason)
      }

      // 处理最新文章
      if (recentBlogsResult.status === 'fulfilled') {
        const recentBlogsData = recentBlogsResult.value
        if (recentBlogsData && recentBlogsData.records && recentBlogsData.records.length > 0) {
          recentPosts.value = recentBlogsData.records.map(blog => transformBlogToBlogPost(blog))
        } else {
          console.log('No recent posts found')
        }
      } else {
        console.error('获取最新文章失败:', recentBlogsResult.reason)
      }

      // 处理热门标签
      if (tagsResult.status === 'fulfilled') {
        const tags = tagsResult.value
        if (tags && tags.length > 0) {
          // 按count排序，取前8个
          popularTags.value = tags
            .sort((a, b) => b.count - a.count)
            .slice(0, 8)
            .map(tag => transformApiTagToTag(tag))
        }
      } else {
        console.warn('获取热门标签失败:', tagsResult.reason)
      }

      // 处理博客分类
      if (categoriesResult.status === 'fulfilled') {
        const categories = categoriesResult.value
        if (categories && categories.length > 0) {
          popularCategories.value = categories.slice(0, 6) // 取前6个分类
        }
      } else {
        console.warn('获取分类失败:', categoriesResult.reason)
        popularCategories.value = []
      }

      // 暂时设置空的最近评论（新系统中需要不同的实现方式）
      recentComments.value = []

      // 性能统计
      const endTime = performance.now()
      const loadTime = Math.round(endTime - startTime)
      console.log(`🚀 首页数据加载完成，耗时: ${loadTime}ms`)

      // 统计成功和失败的请求数量
      const results = [
        userInfoResult,
        topPostsResult,
        recentBlogsResult,
        tagsResult,
        categoriesResult,
      ]
      const successCount = results.filter(result => result.status === 'fulfilled').length
      const failureCount = results.filter(result => result.status === 'rejected').length

      console.log(`📊 API调用统计: 成功 ${successCount}/5, 失败 ${failureCount}/5`)
    } catch (error) {
      console.error('加载数据失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 处理文章点击
  const handlePostClick = (postId: string) => {
    router.push(`/articles/${postId}`)
  }

  // 处理标签点击
  const handleTagClick = (tag: Tag & { id: string }) => {
    router.push(`/tags/${tag.id}`)
  }

  // 处理分类点击
  const handleCategoryClick = (categoryId: string) => {
    router.push(`/categories?categoryId=${categoryId}`)
  }

  onMounted(async () => {
    await initData()
    user.value = await globalStore.ensureUserInfo()
  })
</script>

<template>
  <div class="new-home">
    <!-- 英雄区域 -->
    <HeroSection />

    <!-- 主内容区域 -->
    <div class="home-content">
      <div class="container">
        <!-- 精选文章轮播（只在有数据时显示） -->
        <section v-if="featuredPosts.length > 0 || loading" class="featured-section">
          <div class="section-header">
            <h2 class="section-title">✨ 精选文章</h2>
            <p class="section-subtitle">推荐阅读的优质内容</p>
          </div>
          <FeaturedPosts :posts="featuredPosts" :loading="loading" @post-click="handlePostClick" />
        </section>

        <!-- 内容网格 -->
        <div class="content-grid">
          <!-- 左侧主要内容 -->
          <div class="main-content">
            <!-- 最新文章 -->
            <section class="recent-section">
              <div class="section-header">
                <h2 class="section-title">📝 最新文章</h2>
                <router-link to="/articles" class="more-link">查看全部 →</router-link>
              </div>
              <RecentPosts :posts="recentPosts" :loading="loading" @post-click="handlePostClick" />
            </section>
          </div>

          <!-- 右侧边栏 -->
          <aside class="sidebar">
            <!-- 网站统计 -->
            <SiteStats />

            <!-- 博客分类 -->
            <section class="categories-section">
              <h3 class="sidebar-title">📁 博客分类</h3>
              <PopularCategories
                :categories="popularCategories"
                @category-click="handleCategoryClick"
              />
            </section>

            <!-- 热门标签 -->
            <section class="tags-section">
              <h3 class="sidebar-title">🏷️ 热门标签</h3>
              <PopularTags :tags="popularTags" @tag-click="handleTagClick" />
            </section>

            <!-- 最近评论 -->
            <section class="comments-section">
              <h3 class="sidebar-title">💬 最近评论</h3>
              <RecentComments :comments="recentComments" @post-click="handlePostClick" />
            </section>
          </aside>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner">
        <div class="spinner"></div>
        <p>正在加载精彩内容...</p>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .new-home {
    min-height: 100vh;
    background-color: var(--bg-color);
  }

  .home-content {
    padding: 2rem 0;
  }

  /* 区块标题 */
  .section-header {
    margin-bottom: 2rem;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
  }

  .section-title {
    font-size: 1.75rem;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  .section-subtitle {
    color: var(--text-secondary);
    margin: 0.5rem 0 0 0;
    font-size: 0.95rem;
  }

  .more-link {
    color: var(--primary-color);
    text-decoration: none;
    font-weight: 500;
    transition: all 0.2s ease;

    &:hover {
      color: var(--primary-hover);
      transform: translateX(2px);
    }
  }

  /* 精选文章区域 */
  .featured-section {
    margin-bottom: 4rem;
  }

  /* 内容网格 */
  .content-grid {
    display: grid;
    grid-template-columns: 1fr 320px;
    gap: 3rem;
    align-items: start;
  }

  .main-content {
    min-width: 0; // 防止内容溢出
  }

  .sidebar {
    position: sticky;
    top: 80px; // 考虑导航栏高度
    display: flex;
    flex-direction: column;
    gap: 2rem;
  }

  .sidebar-title {
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0 0 1rem 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  /* 加载状态 */
  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    backdrop-filter: blur(4px);
  }

  .loading-spinner {
    background-color: var(--bg-color);
    padding: 2rem;
    border-radius: var(--radius-xl);
    box-shadow: var(--shadow-lg);
    text-align: center;
    max-width: 200px;
  }

  .spinner {
    width: 40px;
    height: 40px;
    border: 3px solid var(--border-color);
    border-top: 3px solid var(--primary-color);
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto 1rem;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  .loading-spinner p {
    color: var(--text-secondary);
    margin: 0;
    font-size: 0.9rem;
  }

  /* 响应式设计 */
  @media (max-width: 1024px) {
    .content-grid {
      grid-template-columns: 1fr 280px;
      gap: 2rem;
    }
  }

  @media (max-width: 768px) {
    .content-grid {
      grid-template-columns: 1fr;
      gap: 2rem;
    }

    .sidebar {
      position: static;
      order: -1; // 移动端将侧边栏置顶
    }

    .section-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 0.5rem;
    }

    .section-title {
      font-size: 1.5rem;
    }

    .home-content {
      padding: 1rem 0;
    }
  }

  @media (max-width: 480px) {
    .section-title {
      font-size: 1.3rem;
    }

    .featured-section {
      margin-bottom: 2rem;
    }
  }
</style>
